package com.shirley.myserialportapp.widget

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.widget.TextView
import android.widget.Toast
import com.shirley.myserialportapp.R
import com.shirley.serialportlib.config.CommonBaudRate
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.view_choose_baud_rate.*

/**
 * Description:
 * Created by Shirley
 * Date: 2019/12/6 15:57
 */
class ChooseBaudRateDialog(context: Context) : Dialog(context) {

    private var mListener: OnChooseBaudRateListener? = null

    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.view_choose_baud_rate)
        val displayMetrics = DisplayMetrics()
        (context as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics)
        val layoutParams = window?.attributes
        layoutParams?.width = (displayMetrics.widthPixels * 0.8).toInt()
        window?.attributes = layoutParams
        window?.setGravity(Gravity.CENTER)

        val adapter = object : TagAdapter<Int>(CommonBaudRate.COMMON_BAUD_RATE) {
            override fun getView(parent: FlowLayout?, position: Int, t: Int?): View {
                val tv: TextView =
                    LayoutInflater.from(getContext()).inflate(R.layout.item_baud_rate, parent, false) as TextView
                tv.text = t.toString()
                return tv
            }
        }
        tagFlowLayout.adapter = adapter
        tagFlowLayout.setOnTagClickListener { _, position, _ ->
            mListener?.onChooseBaudRate(CommonBaudRate.COMMON_BAUD_RATE[position])
            dismiss()
            true
        }
        tvYes.setOnClickListener {
            if (etBaudRate.text.toString().isEmpty()) {
                Toast.makeText(context, context.getString(R.string.input_baud_rate_alert), Toast.LENGTH_SHORT).show()
            } else {
                mListener?.onChooseBaudRate(etBaudRate.text.toString().toInt())
                dismiss()
            }
        }
    }

    interface OnChooseBaudRateListener{
        fun onChooseBaudRate(baudRate: Int?)
    }

    fun setOnChooseBaudRateListener(listener: OnChooseBaudRateListener) {
        mListener = listener
    }

}